import React, { Component } from 'react';
//引入antd
import { Form, Icon, Input, Button, Row, Col } from 'antd';
class Login extends Component {
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const userinfo = JSON.parse(
          window.sessionStorage.getItem('user') || ''
        );
        const { history } = this.props;
        //判断数据是否正确
        if (
          values.username !== userinfo.username ||
          values.password !== userinfo.password
        ) {
          alert('用户不存在，请您注册账号');
          history.replace('/register', values);
        } else {
          alert('登陆成功');
          history.replace('/', values);
          return true;
        }
      }
    });
  };
  componentDidMount() {
    const { history } = this.props;
    if (!window.sessionStorage.getItem('user')) {
      alert('您并没有注册记录，请返回注册,(2秒后自动返回)');
      setTimeout(() => {
        history.replace('/register');
      }, 2000);
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Row>
        <Col span={16} offset={4}>
          <Form
            onSubmit={this.handleSubmit}
            autoComplete="off"
            className="login-form"
          >
            <Form.Item>
              {getFieldDecorator('username', {
                rules: [{ required: true, message: '请输入用户名!' }]
              })(
                <Input
                  prefix={
                    <Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />
                  }
                  placeholder="Username"
                />
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码!' }]
              })(
                <Input
                  prefix={
                    <Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />
                  }
                  type="password"
                  placeholder="Password"
                />
              )}
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-form-button"
                block
              >
                Log in
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
    );
  }
}
const LoginFrom = Form.create({ name: 'normal_login' })(Login);
export default LoginFrom;
